package org.jeecg.modules.demo.roomapartdistribute.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.soap.Detail;

import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.applyapartemployee.entity.ZhzfApplyApartEmployeeVo;
import org.jeecg.modules.demo.applyapartemployee.entity.ZnzfApplyApartEmployee;
import org.jeecg.modules.demo.applyapartemployee.service.IZnzfApplyApartEmployeeService;
import org.jeecg.modules.demo.applyapartemployee.service.impl.ZnzfApplyApartEmployeeServiceImpl;
import org.jeecg.modules.demo.checkemployee.entity.ZnzfCheckEmployee;
import org.jeecg.modules.demo.checkemployee.service.IZnzfCheckEmployeeService;
import org.jeecg.modules.demo.projectroom.entity.ZnzfRoom;
import org.jeecg.modules.demo.projectroom.service.IZnzfRoomService;
import org.jeecg.modules.demo.roomapartdistribute.entity.*;
import org.jeecg.modules.demo.roomapartdistribute.service.IZnzfCheckApartRoomListService;
import org.jeecg.modules.demo.roomapartdistribute.service.IZnzfCheckApartService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.demo.roomapartdistribute.service.IZnzfRoomApartDistributeService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 核定单位
 * @Author: jeecg-boot
 * @Date:   2022-03-21
 * @Version: V1.0
 */
@Api(tags="核定单位")
@RestController
@RequestMapping("/roomapartdistribute/znzfCheckApart")
@Slf4j
public class ZnzfCheckApartController extends JeecgController<ZnzfCheckApart, IZnzfCheckApartService> {
	 @Autowired
	 private IZnzfCheckApartService znzfCheckApartService;

	 @Autowired
	 private IZnzfCheckApartRoomListService znzfCheckApartRoomListService;

	 @Autowired
	 private IZnzfCheckEmployeeService znzfCheckEmployeeService;

	 @Autowired
	 private IZnzfApplyApartEmployeeService znzfApplyApartEmployeeService;

	 @Autowired
	 private ISysUserService sysUserService;

	 @Autowired
	 private ISysDepartService sysDepartService;

	 @Autowired
	 private IZnzfRoomApartDistributeService znzfRoomApartDistributeService;

	 @Autowired
	 private IZnzfRoomService znzfRoomService;

	 /**
	  * 分页列表查询
	  *
	  * @param znzfCheckApart
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "核定单位-分页列表查询")
	 @ApiOperation(value = "核定单位-分页列表查询", notes = "核定单位-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<IPage<ZnzfCheckApart>> queryPageList(ZnzfCheckApart znzfCheckApart,
														@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
														@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
														HttpServletRequest req) {
		 QueryWrapper<ZnzfCheckApart> queryWrapper = QueryGenerator.initQueryWrapper(znzfCheckApart, req.getParameterMap());
		 Page<ZnzfCheckApart> page = new Page<ZnzfCheckApart>(pageNo, pageSize);
		 IPage<ZnzfCheckApart> pageList = znzfCheckApartService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 /**
	  * 添加
	  *
	  * @param znzfCheckApart
	  * @return
	  */
	 @AutoLog(value = "核定单位-添加")
	 @ApiOperation(value = "核定单位-添加", notes = "核定单位-添加")
	 @PostMapping(value = "/add")
	 public Result<String> add(@RequestBody ZnzfCheckApart znzfCheckApart) {
		 znzfCheckApartService.save(znzfCheckApart);
		 return Result.OK("添加成功！");
	 }

	 /**
	  * 编辑
	  *
	  * @param znzfCheckApart
	  * @return
	  */
	 @AutoLog(value = "核定单位-编辑")
	 @ApiOperation(value = "核定单位-编辑", notes = "核定单位-编辑")
	 @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> edit(@RequestBody ZnzfCheckApart znzfCheckApart) {
		 znzfCheckApartService.updateById(znzfCheckApart);
		 return Result.OK("编辑成功!");
	 }

	 /**
	  * 通过id删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "核定单位-通过id删除")
	 @ApiOperation(value = "核定单位-通过id删除", notes = "核定单位-通过id删除")
	 @DeleteMapping(value = "/delete")
	 public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
		 znzfCheckApartService.removeById(id);
		 return Result.OK("删除成功!");
	 }

	 /**
	  * 批量删除
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "核定单位-批量删除")
	 @ApiOperation(value = "核定单位-批量删除", notes = "核定单位-批量删除")
	 @DeleteMapping(value = "/deleteBatch")
	 public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		 this.znzfCheckApartService.removeByIds(Arrays.asList(ids.split(",")));
		 return Result.OK("批量删除成功!");
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "核定单位-通过id查询")
	 @ApiOperation(value = "核定单位-通过id查询", notes = "核定单位-通过id查询")
	 @GetMapping(value = "/queryById")
	 public Result<ZnzfCheckApart> queryById(@RequestParam(name = "id", required = true) String id) {
		 ZnzfCheckApart znzfCheckApart = znzfCheckApartService.getById(id);
		 if (znzfCheckApart == null) {
			 return Result.error("未找到对应数据", null);
		 }
		 return Result.OK(znzfCheckApart);
	 }

	 /**
	  * @param radId: 房源单位分配表的id
	  * @Description: 根据房源单位分配表的id查询
	  * @Return: org.jeecg.common.api.vo.Result<org.jeecg.modules.demo.roomapartdistribute.entity.ZnzfCheckApart>
	  */
	 @ApiOperation(value = "核定单位-通过radId查询", notes = "核定单位-通过radId查询")
	 @GetMapping(value = "/queryByRadId")
	 public Result<List<ZnzfCheckApart>> queryByRadId(@RequestParam(name = "radId", required = true) String radId) {
		 List<ZnzfCheckApart> znzfCheckApartList = znzfCheckApartService.searchsByZnzfRoomApartDistributeId(radId);
		 if (znzfCheckApartList == null) {
			 return Result.error("未找到对应数据", null);
		 }
		 return Result.OK(znzfCheckApartList);
	 }

	 /**
	  * @param radId: 房源单位分配表的id
	  * @Description: 根据房源单位分配表的id模糊查询
	  * @Return: org.jeecg.common.api.vo.Result<org.jeecg.modules.demo.roomapartdistribute.entity.ZnzfCheckApart>
	  */
	 @ApiOperation(value = "核定单位-通过radId和name模糊查询", notes = "核定单位-通过radId和name模糊查询")
	 @GetMapping(value = "/queryByRadIdAndName")
	 public Result<Page<ZnzfCheckApartVo>> queryByRadIdAndName(@RequestParam(name = "radId", required = true) String radId,
															   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
															   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
															   @RequestParam(name = "name", required = false) String name) {
		 List<ZnzfCheckApart> znzfCheckApartList = znzfCheckApartService.searchsByZnzfRoomApartDistributeId(radId);
		 List<ZnzfCheckApartVo> znzfCheckApartVoList = new ArrayList<>();
		 if (znzfCheckApartList == null) {
			 Page<ZnzfCheckApartVo> page = new Page<>(pageNo, pageSize);
			 Result<Page<ZnzfCheckApartVo>> result = new Result<Page<ZnzfCheckApartVo>>();
			 page.setSize(pageSize);
			 page.setCurrent(pageNo);
			 page.setTotal(0);
			 page.setPages(1);
			 page.setRecords(znzfCheckApartVoList);
			 result.setResult(page);
			 result.setSuccess(true);
			 return result;
		 }
		 for (ZnzfCheckApart znzfCheckApart : znzfCheckApartList) {
			 ZnzfCheckApartVo znzfCheckApartVo = new ZnzfCheckApartVo();
			 SysDepart sysDepart = sysDepartService.getById(znzfCheckApart.getApartId());
			 if (name != null && !sysDepart.getDepartName().contains(name))
				 continue;
			 znzfCheckApartVo.setApart(sysDepart.getDepartName());
			 znzfCheckApartVo.setId(znzfCheckApart.getId());
			 znzfCheckApartVo.setRoomApartDistributeId(znzfCheckApart.getRoomApartDistributeId());
			 znzfCheckApartVo.setRoomRatio(znzfCheckApart.getRoomRatio());
			 znzfCheckApartVo.setCheckedRoomNum(znzfCheckApart.getCheckedRoomNum());
			 znzfCheckApartVo.setApartCheckPeopleNum(znzfCheckApart.getApartCheckPeopleNum());
			 znzfCheckApartVo.setApplyNumSum(znzfCheckApart.getApplyNumSum());
			 znzfCheckApartVo.setApartCheckPeopleNum(znzfCheckApart.getApartCheckPeopleNum());
			 znzfCheckApartVo.setState(znzfCheckApart.getState());
			 znzfCheckApartVo.setNote(znzfCheckApart.getNote());
//			 znzfCheckApartVo.setCheckedRoomNum(0);
//			 znzfCheckApartVo.setRoomRatio(0.0);
			 znzfCheckApartVo.setApartPeopleApplyRatio(znzfCheckApart.getApartCheckPeopleNum() / (znzfCheckApart.getApplyNumSum() * 1.0));
			 znzfCheckApartVoList.add(znzfCheckApartVo);
		 }
		 Page<ZnzfCheckApartVo> page = new Page<>(pageNo, pageSize);
		 int count = znzfCheckApartVoList.size();
		 List<ZnzfCheckApartVo> pageList = new ArrayList<>();
//计算当前页第一条数据的下标
		 int currId = pageNo > 1 ? (pageSize - 1) * pageSize : 0;
		 for (int i = 0; i < pageSize && i < count - currId; i++) {
			 pageList.add(znzfCheckApartVoList.get(currId + i));
		 }
		 page.setSize(pageSize);
		 page.setCurrent(pageNo);
		 page.setTotal(count);
//计算分页总页数
		 page.setPages(count % 10 == 0 ? count / 10 : count / 10 + 1);
		 page.setRecords(pageList);

		 Result<Page<ZnzfCheckApartVo>> result = new Result<Page<ZnzfCheckApartVo>>();
		 result.setResult(page);
		 result.setSuccess(true);
		 return result;
	 }

	 /**
	  * 导出excel
	  *
	  * @param request
	  * @param znzfCheckApart
	  */
	 @RequestMapping(value = "/exportXls")
	 public ModelAndView exportXls(HttpServletRequest request, ZnzfCheckApart znzfCheckApart) {
		 return super.exportXls(request, znzfCheckApart, ZnzfCheckApart.class, "核定单位");
	 }

	 /**
	  * 通过excel导入数据
	  *
	  * @param request
	  * @param response
	  * @return
	  */
	 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		 return super.importExcel(request, response, ZnzfCheckApart.class);
	 }


	 /**
	  * 根据房源单位分配表的id主键查该表下的所有单位和所有报名人 把所有相同单位的员工都放一起
	  *
	  * @param radId
	  * @param name
	  * @return
	  */
	 @ApiOperation(value = "核定单位-根据房源单位分配表的id主键查该表下的所有单位和所有报名人", notes = "核定单位-根据房源单位分配表的id主键查该表下的所有单位和所有报名人")
	 @GetMapping(value = "/znzfRoomApartSelect")
	 public Result<Page<JSONObject>> znzfRoomApartSelect(@RequestParam(value = "radId",required = true) String radId,
														 @RequestParam(value = "name",required = false) String name,
														 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {

	 	 List<JSONObject> list = new JSONArray();

		 List<ZnzfCheckApart> znzfCheckApartList = znzfCheckApartService.findByRadId(radId);
		 for(ZnzfCheckApart apart : znzfCheckApartList){
			 JSONObject record = new JSONObject();
			 String departName = sysDepartService.getById(apart.getApartId()).getDepartName();
			 if(!"".equals(name) && name != null)//根据部门名称模糊查询
			 	if(!departName.contains(name))
			 		continue;
			if(Integer.parseInt(apart.getState()) <= -1)//审核状态异常
				continue;
			 List<ZnzfCheckApartRoomList> roomLists = znzfCheckApartRoomListService.searchsByZnzfCheckApartId(apart.getId());
			 //单位id
			 record.put("id", apart.getId());
			// 单位
			 record.put("apart", departName);
			 // 总报名人数
			 record.put("applyNumSum", apart.getApplyNumSum().toString());
			 // 核定报名人数
			 record.put("apartCheckPeopleNum", apart.getApartCheckPeopleNum().toString());
			 // 单位人员报名比例
			 record.put("apartPeopleApplyRatio", apart.getApartPeopleApplyRatio()*100 +"%");
			 // 房源占比
			 record.put("roomRatio", apart.getRoomRatio()*100 +"%");
			 // 核定房源数量
			 record.put("checkedRoomNum", apart.getCheckedRoomNum().toString());
			 //审核状态
			 record.put("state",Integer.parseInt(apart.getState()));
             // detail 房源号和姓名
			 List<ZnzfRoomDistributeDetailVo> detail = new ArrayList<>();
			 roomLists.forEach(roomList->{
				 ZnzfRoom room = znzfRoomService.getById(roomList.getRoomId());
				 String realname = sysUserService.userIdToRealname(roomList.getUid());
				 ZnzfRoomDistributeDetailVo item = new ZnzfRoomDistributeDetailVo();
				 item.setRoomInfo(room.getGroupName() + "-" + room.getUnit() + "-" + room.getHouseNo());
				 item.setRealname(realname);
				 detail.add(item);
			 });
			 record.put("detail",detail);
			 list.add(record);
		 }
		 Page<JSONObject> page = new Page<>(pageNo,pageSize);
		 int count = list.size();
		 List<JSONObject> pageList = new ArrayList<>();
		 int currId = pageNo > 1 ? (pageSize - 1) * pageSize : 0;
		 for (int i = 0; i < pageSize && i < count - currId; i++) {
			 pageList.add(list.get(currId + i));
		 }
		 page.setTotal(count);
		 page.setCurrent(pageNo);
		 page.setSize(pageSize);
		 // 计算分页总页数
		 page.setPages(count % 10 == 0 ? count / 10 : count / 10 + 1);
		 page.setRecords(pageList);

		 Result<Page<JSONObject>> result = new Result<>();
		 result.setResult(page);
		 result.setSuccess(true);
		 return result;
	 }


	 /**
	  * 查询核定部门下所有已入围的人
	  *
	  * @param radId 核定部门主键
	  * @param  employeeName 用户姓名 (为空就是查询所有,不为空为模糊查询)
	  * @return
	  */
	 @ApiOperation(value = "核定单位-查询单位房源分配id下所有的人", notes = "核定单位-查询单位房源分配id下所有的人")
	 @GetMapping(value = "/queryEmployeeChecked")
	 public Result<Page<EmployeeCheckedParam>> queryEmployeeChecked(HttpServletRequest request,
																	@RequestParam(name = "radId", required = true) String radId,
																	@RequestParam(name = "employeeName", required = false) String employeeName,
																	@RequestParam(name = "departName", required = false) String departName,
																	@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
																	@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {


		 String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		 String tmp = JwtUtil.getUsername(token);
		 SysUser sysUser = sysUserService.getUserByName(tmp);
		 if (sysUser == null)
			 return Result.error("账号异常");
//		 SysDepart sysDepart = sysDepartService.searchByOrgCode(sysUser.getOrgCode());
//		 ZnzfCheckApart znzfCheckApart = znzfCheckApartService.searchByZnzfRoomApartDistributeIdAndApartId(radId, sysDepart.getId());
//		 ZnzfCheckApart znzfCheckApart = znzfCheckEmployeeService.findApartByUserId(uid);
//
//
//		 if (znzfCheckApart == null) return Result.error("未找到对应数据", null);
		 List<EmployeeCheckedParam> employeeCheckedParamList = new LinkedList<>();
		 List<ZnzfCheckApart> znzfCheckApartList = znzfCheckApartService.searchsByZnzfRoomApartDistributeId(radId);
		 for (ZnzfCheckApart znzfCheckApart : znzfCheckApartList) {
			 List<ZnzfCheckEmployee> znzfCheckEmployeeList = znzfCheckEmployeeService.findCheckedEmployListByCheckApartId(znzfCheckApart.getId());

			 if (znzfCheckEmployeeList != null) {
				 for (ZnzfCheckEmployee item:znzfCheckEmployeeList) {
					 SysUser user = sysUserService.getById(item.getUserId());
					 String userId = user.getId();
					 SysDepart depart = sysDepartService.getById(znzfCheckApart.getApartId());
					 if (employeeName != null && !user.getRealname().contains(employeeName))
						 continue;
					 if (departName != null && !depart.getDepartName().contains(departName))
						 continue;
					 EmployeeCheckedParam employeeCheckedParam = new EmployeeCheckedParam();
					 employeeCheckedParam.setId(item.getId());
					 // 获取并设置入围人员真实姓名
					 String realName = sysUserService.userIdToRealname(item.getUserId());
					 employeeCheckedParam.setName(realName);
					 // 获取并设置入围人员电话号码
					 String tel = znzfCheckEmployeeService.findTelByUserId(item.getUserId());
					 employeeCheckedParam.setTel(tel);
					 // 设置入围人员申请时间
					 employeeCheckedParam.setApplyTime(item.getApplyTime());
					 // 设置入围人员分数
					 employeeCheckedParam.setScore(item.getScore());
					 // 设置所属部门
					 employeeCheckedParam.setDepart(depart.getDepartName());
					 employeeCheckedParamList.add(employeeCheckedParam);
				 }
			 }
		 }

		 // 返回列表为空时
		 if (employeeCheckedParamList.isEmpty()) {
			 Page<EmployeeCheckedParam> page = new Page<>(pageNo, pageSize);
			 Result<Page<EmployeeCheckedParam>> result = new Result<Page<EmployeeCheckedParam>>();
			 page.setSize(pageSize);
			 page.setCurrent(pageNo);
			 page.setPages(1);
			 page.setTotal(0);
			 page.setRecords(employeeCheckedParamList);
			 result.setResult(page);
			 result.setSuccess(true);
			 return result;
		 }
		 // 返回列表不为空时
		 Page<EmployeeCheckedParam> page = new Page<>(pageNo, pageSize);
		 int count = employeeCheckedParamList.size();
		 List<EmployeeCheckedParam> pageList = new ArrayList<>();
		 // 计算当前页第一条数据的下标
		 int currId = pageNo > 1 ? (pageSize - 1) * pageSize : 0;
		 for (int i = 0; i < pageSize && i < count - currId; i++) {
			 pageList.add(employeeCheckedParamList.get(currId + i));
		 }
		 page.setTotal(count);
		 page.setCurrent(pageNo);
		 page.setSize(pageSize);
		 // 计算分页总页数
		 page.setPages(count % 10 == 0 ? count / 10 : count / 10 + 1);
		 page.setRecords(pageList);

		 Result<Page<EmployeeCheckedParam>> result = new Result<Page<EmployeeCheckedParam>>();
		 result.setResult(page);
		 result.setSuccess(true);
		 return result;
	 }

	 @AutoLog(value = "核定单位-更改所有核定单位的房源数量")
	 @ApiOperation(value = "核定单位-更改所有核定单位的房源数量", notes = "核定单位-更改所有核定单位的房源数量")
	 @PostMapping(value = "/saveCheckApartRoom")
	 public Result<String> saveCheckApartRoom(HttpServletRequest request, @RequestBody List<ZnzfCheckApart> znzfCheckApartList) {
		 String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		 String name = JwtUtil.getUsername(token);
		 SysUser sysUser = sysUserService.getUserByName(name);
		 if (name == null || sysUser == null)
			 return Result.error("账号异常");
		 for (ZnzfCheckApart znzfCheckApart : znzfCheckApartList) {
			 znzfCheckApartService.updateById(znzfCheckApart);
		 }
		 return Result.ok("更新分配结果成功");
	 }

}
